// import Taro from '@tarojs/taro';
// import Login from '@utils/login'

import { MINA_VERSION } from "../config/index";
import { HOST } from "../config/index";

const getDefaultHeader = {
  "content-type": "application/json",
  mina_version: MINA_VERSION,
};
const postDefaultHeader = {
  "content-type": "application/x-www-form-urlencoded",
  mina_version: MINA_VERSION,
};

let reLogin = 0;

const http = {
  request(
    { url, data = {}, header, loading = true, method = "POST" },
    checkoutLogin = true,
    requestTimes = 1
  ) {
    // if (loading) {
    //   Taro.showLoading({
    //     title: "加载中"
    //   });
    // }
    return new Promise((resolve, reject) => {
      let _url = url;
      const sessionId = Taro.getStorageSync("sessionId") || "";
      if (checkoutLogin) {
        _url += `${url.includes("?") ? "&" : "?"}sessionId=${sessionId}`;
        data.sessionId = sessionId;
      }

      const isUrl = /https:|http:|\/\//.test(_url);
      const timer = setTimeout(() => {
        Taro.stopPullDownRefresh();
      }, 300);
      Taro.request({
        method,
        url: isUrl ? _url : `${HOST}${_url}`,
        data,
        header: Object.assign(getDefaultHeader, header, {}),
      })
        .then((res) => {
          // Taro.stopPullDownRefresh() // 关闭下拉动画
          clearTimeout(timer);
          // if (loading) Taro.hideLoading();
          responseProxy({ ...res }, sessionId)
            .then((data) => {
              resolve(data);
            })
            .catch((err) => {
              reject(err);
            });
        })
        .catch((err) => {
          if (loading) Taro.hideLoading();
          Taro.showToast({
            content: "网络异常，请稍后再试！",
            type: "fail",
          });
          Taro.stopPullDownRefresh(); // 关闭下拉动画
          clearTimeout(timer);
          reject();
        });
    });
  },
};

/**
 * @desc 处理http返回的请求。
 * @param response
 */
function responseProxy({ data }, sessionId) {
  return new Promise((resolve, reject) => {
    const { status, message } = data;
    if (status === "2000000") {
      resolve(data);
    } else if (status === "666") {
      // 未注册
      resolve(data);
    } else if (status === "-3") {
      // 超时，重试3次
      reject();
    } else if (["5000101", "5000102", "5000103", "5000104"].includes(status)) {
      // if(status === "5000104"){
      //   Login.initJsCode();
      // }
      if (sessionId.length) {
        Taro.showToast({
          title: "用户已过期, 正在重新登录",
          icon: "none",
          duration: 3000,
        });
        setTimeout(function () {
          Login.login().then(({ isRegister }) => {
            if (!isRegister) {
              Taro.setStorageSync("sessionId", null);
            } else {
              Taro.showToast({
                title: "登录成功",
                icon: "success",
                duration: 2000,
              });
            }
          });
        }, 2000);
      } else {
        Taro.showToast({
          title: "请先注册",
          icon: "none",
          duration: 1000,
        });
        setTimeout(function () {
          Taro.redirectTo("pages/my/index");
        }, 2000);
      }
      reject(status);
    } else if (
      status === "5000000" &&
      message === "用户已完成实名认证，无须重复操作"
    ) {
      reject(status);
    } else {
      Taro.showToast({
        title: message,
        icon: "none",
        duration: 3000,
      });
      reject(status);
    }
  });
}

export default http;
